package com.yanghui.lingyue.functions.apiBase

import com.icedata.sika.bridge.SikaEvent
import com.icedata.sika.bridge.SikaGroupEvent
import com.icedata.sika.bridge.SikaUserEvent
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.Sika
import com.icedata.sika.util.Logger
import com.yanghui.lingyue.bot.Bot
import com.yanghui.lingyue.data.Command
import com.yanghui.lingyue.data.Operation
import com.yanghui.lingyue.functions.AbstractFunction
import com.yanghui.lingyue.utils.functionUtils.FunctionUtils
import com.yanghui.lingyue.utils.netUtils.HttpJsonUtils
import java.util.*

object SendMotto : AbstractFunction() {
    override val name = "Motto"

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent) return command
        event as SikaGroupEvent
        if (!FunctionUtils.atBot(event)) return command
        if (!FunctionUtils.checkValid(event)) return command
        if (event.sendGroup.id !in enableGroup) return command

        val param = FunctionUtils.extractKeyword(event, "MOTTO")
        param?.let {
            command.add(Command(event, name, it))
        }
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        val operation = Operation(command)
        Bot.sikaCore.databaseInsert(operation)
        try {
            val motto = HttpJsonUtils.getJsonObjectFromURLMethodGet(
                "https://v1.hitokoto.cn/?c=d&c=i&encode=json"
            )
            command.sendGroup?.sendMessage(
                "${motto.getString("hitokoto")}\n ——${motto.getString("from_who")} ${motto.getString("from")}".replace(
                    "null",
                    ""
                )
            )
            return CommandProcessor.Result.ADOPT
        } catch (e: Exception) {
            Logger.logError(e)
            command.sendGroup?.sendMessage("获取Motto错误")
            return CommandProcessor.Result.ADOPT
        }
    }
}